import re

from django.contrib.auth.backends import ModelBackend
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData
from .models import User
from django.conf import settings


def get_by_account(account):
    """
    根据account查询用户
    :param account: 用户名或者手机号
    :return: user
    """
    try:
        if re.match('^1[3-9]\d{9}$', account):
            # 手机登陆
            user1 = User.objects.get(mobile=account)

        else:
            # 用户登入
            user1 = User.objects.get(username=account)
    except User.DoesNotExist:
        return None

    return user1


class UsernameMobileAuthBackend(ModelBackend):
    """自定义用户认真后端"""

    def authenticate(self, username=None, password=None, **kwargs):
        # 1.查询到user   可以动态通过手机号或用户名
        user = get_by_account(username)
        # 2.校验user的密码对不对
        if user and user.check_password(password):
            # 3.校验通过把当前的user返回
            return user


def generate_verify_email_url(user):
    """
    生成email验证连接
    :param user: 当前等人用户
    :return: verify_url
    """
    """拼接用户邮箱激活url"""
    # 创建加密对象
    serializer = Serializer(settings.SECRET_KEY, 60 * 60 * 24)
    # 包装要加密的字典数据
    data = {'user_id': user.id, 'email': user.email}
    # 对字典进行加密
    token = serializer.dumps(data).decode()
    # 拼接用户激活邮箱url
    verify_url = settings.EMAIL_VERIFY_URL + '?token=' + token

    return verify_url


def check_verify_email_token(token):
    """对token进行解密并返回user或None"""
    # 创建加密对象
    # 创建加密对象
    serializer = Serializer(settings.SECRET_KEY, 60 * 60 * 24)
    try:
        # 解密
        data = serializer.loads(token)
        # 解密没有问题后取出里面数据
        user_id = data.get('user_id')
        email = data.get('email')
        try:
            user = User.objects.get(id=user_id, email=email)
            return user  # 查询到直接返回
        except User.DoesNotExist:
            return None
    except BadData:
        return None
